#!/usr/bin/env python

from socket import socket, AF_INET, SOCK_STREAM

print "Building socket..."

s = socket(AF_INET, SOCK_STREAM, 0)
s.bind(("127.0.0.1", 6567))
s.listen(1)
print "Waiting for client..."

try:
    while True:
        c, addr = s.accept()
        print "<< Client connected"
        try:
            while True:
                data = ""
                while "\0" not in data:
                    d = c.recv(1024)
                    if len(d) == 0:
                        raise "discon"
                    data += d
                print data
                try:
                    while True:
                        line = raw_input("]> ")
                        c.send('\n'.join(line.split(' '))+"\n")
                except EOFError:
                    print "\r<EOC>"
                    c.send("\0\n")
        except "discon":
            print "<< Connection lost"
            c.close()

except KeyboardInterrupt:
    print "Exiting."
    s.close()
